<template>
    <div class="FormPcPdfTemp">
        <div class="FormPcPdfTemp-head">
            <img class="FormPcPdfTemp-head-img" src="@/image/pdf.png">
            <div class="FormPcPdfTemp-head-name">{{i18n('printTemplate','打印模板')}}</div>
            <div style="flex: 1">
                <a-form :form="form">
                    <a-form-item style="display: none">
                        <a-input v-decorator="['id']"/>
                    </a-form-item>
                    <a-row>
                        <a-col :span="8">
                            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol"
                                         :label="$ti18('rxForm.name','名称')">
                                <div style="display: flex">
                                  <div style="flex: 1">
                                    <a-input :placeholder="$ti18('rxForm.name','名称')"
                                             v-decorator="['name', {rules: [{required: true, message: $ti18('rxForm.name','名称','','input')}]}]"/>
                                  </div>
                                  <div style="padding-left: 6px;">
                                    <a-tooltip>
                                      <template slot="title">
                                        <ul>
                                          双值字段显示
                                          <li>
                                            ${data.属性} 显示文本
                                          </li>
                                          <li>
                                            ${data.属性:v}显示值
                                          </li>
                                          <li>
                                            ${data.属性:b}两个都显示
                                          </li>
                                        </ul>
                                      </template>
                                      <a-icon type="question-circle" />
                                    </a-tooltip>
                                  </div>
                                </div>
                            </a-form-item>
                        </a-col>

                    </a-row>
                </a-form>

            </div>
        </div>
        <div class="FormPcPdfTemp-common">
            <div class="FormPcPdfTemp-common-le center-collapse">
                <div style="flex: 1">
                    <a-tabs default-active-key="1">
                        <a-tab-pane key="1" :tab="i18n('form.formField','表单字段')">
                            <a-collapse :activeKey="activeKey" :bordered="false">
                                <template #expandIcon="props">
                                    <a-icon type="caret-right" :rotate="props.isActive ? 90 : 0"/>
                                </template>
                                <a-collapse-panel style="position: relative" v-for="(def,index) in boList" :key="index">
                                    <template #extra>
                                        <div class="collapse-head">
                                            <a-tag v-if="def.type=='main'" color="#02c5b7">{{i18n('form.mainTable','主表')}}</a-tag>
                                            <a-tag v-if="def.type=='onetomany'" color="#ffa752">{{i18n('form.onetoManySubTable','一对多子表')}}</a-tag>
                                            <a-tag v-if="def.type=='onetoone'" color="#93a8ff">{{i18n('form.oneToOneSubTable','一对一子表')}}</a-tag>
                                            <span v-if="def.name">{{ def.name }}</span>
                                        </div>
                                    </template>
                                    <div v-for="attr in def.children" :key="attr.alias">
                                        <div class="collapse-list" :class="'collapse-list-'+def.type">
                                            <img class="collapse-list-img" :src="boAttrListImg(attr,def.type)">
                                            <div class="collapse-list-filter">{{ attr.title }}({{ attr.name }})</div>
                                            <div class="collapse-list-interposition">
                                                <a @click="selectBoNode(def,attr,'label')">{{i18n('form.insertLabel','插入标签')}}</a>
                                                <a @click="selectBoNode(def,attr,'alias')">{{i18n('form.insertTemplate','插入模板')}}</a>
                                            </div>
                                        </div>
                                    </div>
                                </a-collapse-panel>
                            </a-collapse>
                        </a-tab-pane>
                        <a-tab-pane key="2" :tab="i18n('form.systemField','系统字段')" force-render>
                            <a-collapse :activeKey="activeKey" :bordered="false">
                                <template #expandIcon="props">
                                    <a-icon type="caret-right" :rotate="props.isActive ? 90 : 0"/>
                                </template>
                                <a-collapse-panel style="position: relative" v-for="(def,index) in systemField"
                                                  :key="index">
                                    <template #extra>
                                        <div class="collapse-head">
                                            <span>{{ def.title }}</span>
                                        </div>
                                    </template>
                                    <div v-for="attr in def.children" :key="attr.alias">
                                        <div class="collapse-list" :class="'collapse-list-'+def.type">
                                            <img class="collapse-list-img" :src="boAttrListImg(attr,def.type)">
                                            <div class="collapse-list-filter">{{ attr.title }}({{ attr.name }})</div>
                                            <div class="collapse-list-interposition">
                                                <a @click="systemAdd(def,attr,'label')">{{i18n('form.insertLabel','插入标签')}}</a>
                                                <a @click="systemAdd(def,attr,'alias')">{{i18n('form.insertTemplate','插入模板')}}</a>
                                            </div>
                                        </div>
                                    </div>
                                </a-collapse-panel>
                            </a-collapse>
                        </a-tab-pane>
                    </a-tabs>
                </div>
            </div>
            <div class="FormPcPdfTemp-common-ri">
                <myEditor ref="myEditor" @rxEditor="rxEditor" @addContainer="addContainer" @CustomButton="CustomButton" v-if="myEditorShow" :setting="setting"
                          v-model="pdfHtml" :paper="paper"></myEditor>
            </div>
        </div>
        <!--二维码抽屉-->
        <a-drawer
            :title="i18n('config','配置')"
            placement="right"
            :closable="false"
            :visible="visible"
            :zIndex="2000"
            :width="350"
            @close="visible=false"
        >
            <QrcodeSetting v-if="setting.type=='qrcode'" :setting="setting" :boDefId="boDefId" :bo-list="boList"></QrcodeSetting>
            <BarCodeSetting v-else  :setting="setting" :bo-list="boList"></BarCodeSetting>
        </a-drawer>
        <!--容器抽屉-->
        <a-drawer
            :title="i18n('containerConfig','容器配置')"
            placement="right"
            :closable="false"
            :visible="containerShow"
            :zIndex="2000"
            :width="350"
            @close="containerShow=false"
        >
            <containerCode :setting="setting"></containerCode>
        </a-drawer>
    </div>
</template>

<script>
import FormPcApi from "@/api/form/core/formPc"
import FormPdfTemplateApi from "@/api/form/core/formPdfTemplate"
import {BaseForm, Util} from "@lowcode/jpaas-common-lib";
import VueUeditorWrap from 'vue-ueditor-wrap'
import myEditor from '@/components/myEditor/myEditor.vue';
import QrcodeSetting from "@/views/modules/form/core/pdfTemplate/QrcodeSetting";
import BarCodeSetting from "@/views/modules/form/core/pdfTemplate/BarCodeSetting";
import SystemFields from "@/views/modules/form/core/pdfTemplate/systemFields";
import containerCode from "@/views/modules/form/core/pdfTemplate/containerCode";
import img from "@/image/PRINT_TQR_.png";

export default {
    name: "FormPcPdfTemp2",
    props: ["boDefId", "templates"],
    mixins: [BaseForm],
    components: {
        QrcodeSetting,
        VueUeditorWrap,
        BarCodeSetting,
        myEditor,
        containerCode
    },
    data() {
        return {
            pdfHtml: '',
            boData: [],
            boList: [],
            label: false,
            activeKey: "0",
            //系统字段
            systemField: SystemFields,
            visible: false,
            //二维码列表
            extJson: [],
            //当前选中的
            setting: {},
            key:Util.randomId(),
            containerShow:false,
            myEditorShow:false,
            paper:{

            },//纸张配置
        }
    },
    created() {
        if (this.templates) {
            this.genHtml();
        }
        this.getBoDefConstruct();
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "pdfTemplate.temp2", key);
        },
        genHtml() {
            FormPcApi.generatePrintHtml({boDefId: this.boDefId, genTab: false, templates: this.templates}).then(res => {
                this.pdfHtml = res.data.formTab + "<div><br/></div>";
                this.myEditorShow = true
            })
        },
        onload_(values) {
            if (values) {
                this.boDefId = values.boDefId;
                this.pdfHtml = values.pdfHtml;
                if (values.extJson) {
                    this.extJson = JSON.parse(values.extJson);
                }
                if(values.paper){
                  this.paper = JSON.parse(values.paper);
                }
                this.key=Util.randomId();
            }else {
                this.paper = {
                    paperWidth: 210,
                    paperHeight: 297,
                    paperType: 'A4',
                    direction:'cross'
                }
            }
        },
        get(id) {
            return FormPdfTemplateApi.get(id);
        },
        save(values) {
            values.boDefId = this.boDefId;
            values.pdfHtml = this.pdfHtml;
            let obj = this.$refs.myEditor
            let paper = {
              paperType:obj.paperType,
              paperWidth:obj.paperWidth,
              paperHeight:obj.paperHeight,
              direction:obj.direction
            }
            values.extJson = JSON.stringify(this.extJson);
            values['paper'] = JSON.stringify(paper)
            return FormPdfTemplateApi.save(values);
        },
        handleSubmit(self, this_) {
            this_.form.validateFields((err, values) => {
                if (err) {
                    return;
                }
                values.pkId = this_.pkId;
                this_.confirmLoading = true;
                if (this_.validForm) {
                    var flag = this_.validForm(values);
                    if (!flag) {
                        return;
                    }
                }
                this_.onSubmit(values);
                this_.save(values).then(res => {
                    if (res.success && res.code == 200) {
                        Util.closeWindow(self, "ok");
                    }
                }).catch(() => {
                    this_.$message.error(this_.$ti18('rxMsa.sysError', '系统错误，请稍后再试!'))
                }).finally(() => {
                    this_.confirmLoading = false
                })
            })
        },
        getBoDefConstruct() {
            FormPcApi.getBoDefConstruct(this.boDefId).then(res => {
                if (res.success) {
                    this.boData = res.data;
                    this.changeBoList();
                    this.myEditorShow = true
                }
            });
        },
        changeBoList() {
            let mainList = [];
            this.boData.filter(res => {
                if (res.type == 'main') {
                    mainList.push(res)
                }
            })
            this.boList.push({
                type: 'main',
                children: mainList

            })
            this.boData.filter(res => {
                if (res.type != 'main') {
                    this.boList.push(res)
                }
            })
        },
        boAttrListImg(obj, type) {
            let name = '';
            let i = '';
            if (obj.dataType == 'varchar') {
                name = 'str'
            } else if (obj.dataType == 'number') {
                name = 'number'
            } else {
                name = 'date'
            }
            if (type == 'main') {
                i = '1'
            } else if (type == 'onetomany') {
                i = '2'
            } else {
                i = '3'
            }
            let img = name + i;
            return require('@/image/' + img + '.png')
        },
        selectBoNode(def, item, name) {
            if (!item.isField) {
                return;
            }
            var html = "";
            if (name == 'label') {
                html = item.title
            } else {
                if (def.type == "main") {
                    html = "${data." + item.name + "}"
                } else if (def.type == 'onetomany') {
                    html = "${item." + item.name + "}"
                } else if (def.type == 'onetoone') {
                    html = "${data." + def.name + "." + item.name + "}"
                }
            }
            //插入文本
            this.$refs.myEditor.insertContent(html)
        },
        async systemAdd(def, item, name) {
            let html = "";
            //系统基础字段
            if (name == 'label') {
                html = item.title
            } else if (item.name == 'PRINT_QR_') {

                const img = require('@/image/PRINT_QR_.jpg');
                let id = Util.randomId();
                let obj={
                    id: id,
                    //横位置
                    cross: 'right',
                    //竖位置
                    anyway: 'top',
                    //mm
                    crossNumber: 5,
                    //mm
                    anywayNumber: 5,
                    //mm
                    size: 150,

                    type:"qrcode",
                    content: 'view',
                    //自定义内容
                    customContent: '',
                    //表单方案
                    formSolution:''
                };
                this.extJson.push(obj);
                html = `<img id='${id}' alt='qrcode' style='width: ${obj.size}px;height: ${obj.size}px;position: absolute;right:5mm;top:5mm;z-index: 99' src='${img}'/>`;
            } else if (item.name == 'PRINT_TQR_') {
                //插入条形码
                let id = Util.randomId();

                const img = require('@/image/PRINT_TQR_.png');

                let obj={
                    id: id,
                    //横位置
                    cross: 'left',
                    //竖位置
                    anyway: 'top',
                    //mm
                    crossNumber: 5,
                    //mm
                    anywayNumber: 5,
                    //mm
                    width: 150,
                    height: 60,
                    type:"barcode",
                    //自定义内容
                    customContent: '',
                };
                this.extJson.push(obj);
                html = `<img id='${id}' alt='barcode' style='width: ${obj.width}px;height: ${obj.height}px;position: absolute;left:10px;top:10px;z-index: 99' src='${img}'/>`;
            } else {
                html = "${data." + item.name + "}"
            }
            //插入文本
            this.$refs.myEditor.insertContent(html)
        },
        rxEditor(id) {
            this.extJson.filter(res => {
                if (res.id == id) {
                    this.setting = res;
                }
            })
        },
        //自定义按钮
        CustomButton(type){
            if(type =='delete'){
                this.$refs.myEditor.containerDelete(this.setting.id)
                let index = 0
                this.extJson.filter(res=>{
                    if(res.id==this.setting.id){
                        this.extJson.splice(index,1)
                    }
                    index++;
                })
            }else if(this.setting.id.includes('container')) {
                this.containerShow = true
            }else {
                this.visible = true
            }
        },
        addContainer(obj){
            this.extJson.push(obj)
        }


    },

}
</script>

<style lang="less">
.rx-customContent{
    display: flex;
    flex-wrap: wrap;
    border: 1px solid #e6e6e6;
    min-height: 300px;
    border-radius: 5px;
    padding: 10px;
}
.rx-customContent-item{
    margin: 10px;
    cursor: pointer;
}
.rx-customContent-item:hover{
    color: #1890ff;
}
.rx-custom {
    display: flex;
}

.rx-custom-le {
    color: rgba(0, 0, 0, 0.85);
    font-size: 14px;
    flex: 1;
}

.rx-custom-ri {
    color: #1890ff;
    font-size: 14px;
    cursor: pointer;
}
.FormPcPdfTemp {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
}

.FormPcPdfTemp-head {
    height: 60px;
    display: flex;
    align-items: center;
}

.FormPcPdfTemp-head-img {
    height: 30px;
    margin-top: -16px;
}

.FormPcPdfTemp-head-name {
    font-size: 16px;
    color: #000000;
    margin-top: -12px;
    margin-left: 10px;
}

.FormPcPdfTemp-common {
    flex: 1;
    overflow: auto;
    display: flex;
}

.FormPcPdfTemp-common-le {
    width: 320px;
    height: 100%;
    display: flex;
    flex-direction: column;
    border-top: 1px solid #e6e6e6;
    border-bottom: 1px solid #e6e6e6;
}

.FormPcPdfTemp-common-ri {
    flex: 1;
    height: 100%;
    overflow: auto;
    border-right: 1px solid #e6e6e6;
}

.center-collapse {
    .ant-collapse-content-box {
        padding: 5px 0px !important;
    }

    .collapse-list {
        height: 30px;
        line-height: 30px;
        font-size: 13px;
        padding: 0px 20px;
        color: #000000;
        cursor: pointer;
        display: flex;
        align-items: center;

        a {
            margin-left: 10px;
        }
    }

    .collapse-list:hover .collapse-list-interposition {
        display: block;
    }

    .collapse-list-interposition {
        display: none;
    }

    .collapse-list-filter {
        flex: 1;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }

    .collapse-list-system:hover {
        background: #dafaf8;
    }

    .collapse-list-system i {
        color: #02c5b7;
        font-size: 20px;
        margin-right: 5px;
    }

    .collapse-list-print:hover {
        background: #fdeee0;
    }

    .collapse-list-print i {
        color: #ffa752;
        font-size: 20px;
        margin-right: 5px;
    }

    .collapse-list-main:hover {
        background: #dafaf8;
    }

    .collapse-list-main i {
        color: #02c5b7;
        font-size: 20px;
        margin-right: 5px;
    }

    .collapse-list-onetomany:hover {
        background: #fdeee0;
    }

    .collapse-list-onetomany i {
        color: #ffa752;
        font-size: 20px;
        margin-right: 5px;
    }

    .collapse-list-onetoone:hover {
        background: #e7ecff;
    }

    .collapse-list-onetoone i {
        color: #93a8ff;
        font-size: 20px;
        margin-right: 5px;
    }

    .ant-collapse-borderless {
        background: white !important;
    }

    .ant-collapse-header {
        height: 40px !important;
        border-bottom: 1px dashed #dedede;
        padding: 0px 0px 0px 20px !important;
    }

    .ant-collapse-item {
        border-bottom: none !important;
    }

    .ant-collapse-arrow {
        left: 0px !important;
    }

    .collapse-head {
        position: absolute;
        top: 9px;
        left: 20px;
        z-index: 999;
    }

    .ant-collapse-content-box {
        padding-bottom: 0px;
    }

    .ant-collapse-expand-icon {
        margin-top: 7px;
        margin-left: -16px;
    }
}

.collapse-list-img {
    width: 23px;
    margin-right: 4px;
}
</style>